package com.eyaomall.wxmall.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.eyaomall.wxmall.common.error.BECode;
import com.eyaomall.wxmall.common.helper.MemberHelper;
import com.eyaomall.wxmall.common.util.DateUtils;
import com.eyaomall.wxmall.dao.DiscountGoodsDao;
import com.eyaomall.wxmall.dao.DiscountRecordDao;
import com.eyaomall.wxmall.dao.DiscountRelationDao;
import com.eyaomall.wxmall.model.po.DiscountGoods;
import com.eyaomall.wxmall.model.po.DiscountRelation;
import com.eyaomall.wxmall.model.vo.DiscountGoodsVO;
import com.eyaomall.wxmall.model.vo.DiscountRecordVO;
import com.eyaomall.wxmall.service.DiscountGoodsService;
import com.lycheeframework.core.cmp.kit.PageHTTPObject;
import com.lycheeframework.core.cmp.kit.Pages;
import com.lycheeframework.core.exception.ErrorCodeException;
/**
 * 砍价服务
 * @author yuhuafeng
 * @date 2016-9-7
 */
@Service
public class DiscountGoodsServiceImpl implements DiscountGoodsService {

	@Autowired
	private DiscountGoodsDao discountGoodsDao;
	
	@Autowired
	private DiscountRecordDao discountRecordDao;
	
	@Autowired
	private DiscountRelationDao discountRelationDao;
	/**
	 * 分页查询商品砍价活动
	 * @param vo
	 * @param httpObject
	 * @return
	 */
	public Pages<?> page(DiscountGoods vo, PageHTTPObject httpObject) {
	
		return discountGoodsDao.page(vo, httpObject);
	}


	/**
	 * 分页查询商品砍价活动,根据自定义规则，分页查询商品砍价活动,根据自定义规则,进行中的活动优先级最高，即将开始的中等，已经结束的最低
	 * @param vo
	 * @param httpObject
	 * @return
	 */
	public Pages<?> pageByCustom(DiscountGoods vo, PageHTTPObject httpObject) {
	
		return discountGoodsDao.page("pageByCustom",vo, httpObject);
	}
	/**
	 * 分页查询用户砍价活动记录
	 * @param vo
	 * @param httpObject
	 * @return
	 */
	public Pages<?> pageRecord(DiscountRecordVO vo, PageHTTPObject httpObject) {
		return discountRecordDao.page(vo, httpObject);
	}


	/**
	 * 根据活动id获取活动详情
	 * @param discountid
	 * @return
	 */
	public DiscountGoodsVO queryById(Integer discountid) {
		if(discountid==null)
			throw new ErrorCodeException(BECode.global_900001);
		return (DiscountGoodsVO) discountGoodsDao.query("queryById", discountid);
	}


	/**
	 * 参加砍价活动
	 * @param discountid 活动id
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public Integer join(Integer discountid,Integer num) {
		if(discountid==null||num==null||num<1)
			throw new ErrorCodeException(BECode.global_900001);
		//获取用户信息
		if(MemberHelper.getId()==0||MemberHelper.getId()==null)
			throw new ErrorCodeException(BECode.global_900008);
		//查询活动详情
		DiscountGoodsVO vo=queryById(discountid);
		if(vo==null)
			throw new ErrorCodeException(BECode.discount_6000001);
		if(!"1".equals(vo.getStatus()))
			throw new ErrorCodeException(BECode.discount_6000004);
		if(vo.getGmtEnd().getTime()<new Date().getTime())
			throw new ErrorCodeException(BECode.discount_6000002);
		if(vo.getGmtStart().getTime()>new Date().getTime())
			throw new ErrorCodeException(BECode.discount_6000003);
		
		//开始添加用户活动记录,生成活动记录对象
		DiscountRecordVO recordvo=new DiscountRecordVO();
		recordvo.setDiscountId(discountid);
		recordvo.setMemberId(MemberHelper.getId());//此处对接接口
		recordvo.setGmtStart(new Date());
		//查询用户是否已经参与过改活动，以及是否正在活动中
		DiscountRecordVO record=(DiscountRecordVO) discountRecordDao.query("queryRecord", recordvo);
		if(record!=null){
			//业务修改，可以重复参加活动
//			if("1".equals(record.getIssuccess()))
//			throw new ErrorCodeException(BECode.discount_6000006);
			throw new ErrorCodeException(BECode.discount_6000005);
		}
			
		Date end = DateUtils.getTimeByHour(vo.getLimitTime());
		//如果超过了砍价活动结束时间，则以砍价活动结束时间为准
		if(end.getTime()>vo.getGmtEnd().getTime()){
			end=vo.getGmtEnd();
		}
		recordvo.setGmtEnd(end);
		recordvo.setGoodsId(vo.getGoodsId());
		recordvo.setImgUrl(vo.getImgUrl());
		recordvo.setLastPrice(vo.getPrice());
		recordvo.setPrice(vo.getOriPrice());
		recordvo.setOriPrice(vo.getOriPrice());
		recordvo.setNum(num);
		recordvo.setShopName(vo.getShopName());
		recordvo.setTitle(vo.getTitle());
		recordvo.setIssuccess("0");
		recordvo.setClose("n");
		BigDecimal amount=BigDecimal.ZERO;
		//如果参与活动需要直接砍一刀，那么取消下面代码的注释
//		amount=CalculationAmount(vo.getLimitPrice().doubleValue(), vo.getFirstNum());
//		if(discountRecordDao.bargain(discountid,amount)){
//		}else{
//			throw new ErrorCodeException(BECode.discount_6000010);
//		}
		//以上代码为开启用户自己砍价，该砍价不会记录入帮砍记录
		Integer id=(Integer)discountRecordDao.insert(recordvo);
		if(id>0?true:false){
			//记录砍价信息
			addJoinNum(recordvo.getId(),vo.getGoodsId(), "0",amount,"phone");//此处手机号需要直接从接口获取
			//增加活动参与人数统计
			discountGoodsDao.addJoinNum(discountid);
		}else{
			return 0;
		}
		return recordvo.getId();
	}

	/**
	 * 记录砍价信息
	 * @param discountid 活动id
	 * @param goodsId 商品id
	 * @param type 类型，0为发起人，1为亲友团
	 * @param big 砍掉的余额
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	private boolean addJoinNum(Integer discountid,Integer goodsId,String type,BigDecimal big,String phone){
		//写入参与信息
		DiscountRelation vo=new DiscountRelation();
		vo.setDiscountId(discountid);
		vo.setGoodsId(goodsId);
		vo.setPhone(phone);//此处对接用户手机
		vo.setMemberId(MemberHelper.getId());//此处对接用户id
		vo.setAmount(big);
		vo.setType(type);
		if((Integer)discountRelationDao.insert(vo)>0?true:false){
			
		}else{
			throw new ErrorCodeException(BECode.discount_6000007);
		}
		
		
		return true;
	}


	/**
	 * 根据用户的参与活动的id查询用户活动详情
	 * @param discountid
	 * @return
	 */
	public DiscountRecordVO queryByMemberDiscountId(Integer discountid) {
		
		return (DiscountRecordVO) discountRecordDao.query("queryById", discountid);
	}


	/**
	 * 根据活动id获取所有帮忙砍价记录
	 * @param discountId
	 * @return
	 */
	public Pages<?> queryListLog(Integer discountId,PageHTTPObject httpObject) {
		DiscountRelation vo=new DiscountRelation();
		vo.setDiscountId(discountId);
//		vo.setMemberId(MemberHelper.getId());//此处对接用户接口
		vo.setType("1");
		return discountRelationDao.page("queryListLog", vo,httpObject);
	}


	 /**
	  * 砍价服务
	  * @param discountid 砍价的活动列表
	  * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public boolean bargain(Integer discountid,String phone) {
		
		DiscountRecordVO  record=queryByMemberDiscountId(discountid);//查询该活动详情
		if(record==null)
			throw new ErrorCodeException(BECode.discount_6000001);
		//获取用户信息
//		if(MemberHelper.getId()==0||MemberHelper.getId()==null)
//			throw new ErrorCodeException(BECode.global_900008);
		DiscountGoodsVO vo=queryById(record.getDiscountId());
		if(vo==null)
			throw new ErrorCodeException(BECode.discount_6000001);
		//查看该用户是否拥有砍价资格
		if(discountRelationDao.queryLogByDiscountIdAndPhone(discountid,phone)!=null)
			throw new ErrorCodeException(BECode.discount_6000008);
		//计算砍价金额
		BigDecimal amount=BigDecimal.ZERO;
		//如果已经砍得刀数小于，则按照前几刀余额进行计算
		if(record.getDiscountNum()<vo.getFirstNum()){
		Double balance=	vo.getLimitPrice().doubleValue()-(record.getOriPrice().doubleValue()-record.getPrice().doubleValue());
		if(vo.getFirstNum()-record.getDiscountNum()==1){
			amount=BigDecimal.valueOf(balance);
		}else{
			amount=CalculationAmount(balance,vo.getFirstNum()-record.getDiscountNum());
		}
		}else{
			if(record.getDiscountNum()<vo.getLimitNum()){
				Double balance=	record.getPrice().doubleValue()-record.getLastPrice().doubleValue();
				if(vo.getLimitNum()-record.getDiscountNum()==1){
					amount=BigDecimal.valueOf(balance);
				}else{
					amount=CalculationAmount(balance,vo.getLimitNum()-record.getDiscountNum());
				}
			}else{
				throw new ErrorCodeException(BECode.discount_6000009);
			}
		}
		
		
		//修改现价
		if(discountRecordDao.bargain(discountid,amount)){
		
		//保存砍价信息
		addJoinNum(record.getId(), vo.getGoodsId(), "1",amount,phone);
		
		}else{
			throw new ErrorCodeException(BECode.discount_6000010);
		}
		return true;
	}
	
	
	/**
	 * 砍价金额计算方法
	 * @param total 可以砍掉的余额
	 * @param num 剩余刀数
	 * @return
	 */
	private BigDecimal CalculationAmount(Double total,int num){
		double tmp=(total/num);
		double random=0;
		while(random<=0||random*tmp>=total){
			random=(Math.random()+0.5);
		}
		return new BigDecimal(new DecimalFormat("#.00").format(random*tmp));
		
	}
}
